#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 网络地址和主机地址之间进行转换的类
class InetAddr
{
public:
    InetAddr() = default;
    //网络转主机
    InetAddr(struct sockaddr_in &addr)
    {
        SetAddr(addr);
    }

    //主机转网络
    InetAddr(const std::string& ip, uint16_t port) :_ip(ip), _port(port)
    {
        memset(&_addr, 0, sizeof _addr);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(port);
    }

    //主机转网络 -- 特定针对服务器进行任意地址绑定
    InetAddr(uint16_t port) :_ip("0"), _port(port)
    {
        memset(&_addr, 0, sizeof _addr);
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(port);
    }

    //网络转主机
    void SetAddr(struct sockaddr_in &addr)
    {
        _addr = addr;
        _port = ntohs(_addr.sin_port);
        char ipbuffer[64];
        inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof ipbuffer);
        _ip = ipbuffer;
    }

    uint16_t Port() {return _port;}
    std::string Ip() {return _ip;}
    const struct sockaddr_in& NetAddr() { return _addr; }
    const struct sockaddr* NetAddrPtr() { return (const struct sockaddr*)&_addr; }
    socklen_t AddrLen() {return sizeof _addr;}
    bool operator==(const InetAddr &addr)
    {
        return addr._ip == _ip && addr._port == _port;
    }
    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }
    ~InetAddr()
    {}

private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};